package dao

import (
	"github.com/jinzhu/gorm"
	"go-admin/global"
	"go-admin/internal/model"
	mr "go-admin/internal/model/api/model_request"
	_const "go-admin/internal/model/const"
	"go-admin/pkg/app"
	"time"
)

func (d *Dao) CreateRole(db *gorm.DB, param *mr.CreateRoleRequest) (string, error) {
	role := model.Role{
		CommonModel: model.CommonModel{
			Id:    global.GetId(),
			IsDel: _const.ISDEL,
		},
		IsBanned: _const.ISBANNED,
		RoleName: param.RoleName,
		RoleKey:  param.RoleKey,
	}
	if param.Remark != "" {
		role.Remark = param.Remark
	}
	return role.Id, role.Create(db)
}

// 查询总数
func (d *Dao) CountRole(param *mr.ListRoleRequest) (int, error) {
	role := model.Role{
		IsBanned: param.IsBanned,
		RoleName: param.RoleName,
	}
	return role.Count(d.Engine)
}

// 获取列表
func (d *Dao) GetRoleList(param *mr.ListRoleRequest, pageIndex, pageSize int) ([]*model.Role, error) {
	role := model.Role{
		IsBanned: param.IsBanned,
		RoleName: param.RoleName,
	}
	pageOffset := app.GetPageOffset(pageIndex, pageSize)
	return role.List(d.Engine, pageOffset, pageSize)
}

func (d *Dao) DeleteRoleS(ids []string) error {
	role := model.Role{}
	values := map[string]interface{}{
		"deleted_on": time.Now().Local().Unix(),
		"is_del":     _const.DEL,
	}
	return role.Deletes(d.Engine, ids, values)
}

func (d *Dao) GetRoleByJobNameAndJobCode(param *mr.CreateRoleRequest) (*model.Role, error) {
	role := model.Role{}
	return role.GetRoleByJobNameAndJobCode(d.Engine, param.RoleName, param.RoleKey)
}

// 根据id获取详情
func (d *Dao) GetRoleById(Id string) (*model.Role, error) {
	role := model.Role{
		CommonModel: model.CommonModel{Id: Id},
	}
	return role.GetRoleById(d.Engine)
}

func (d *Dao) UpdateRole(tx *gorm.DB, param *mr.UpdateRoleRequest) error {
	role := model.Role{
		CommonModel: model.CommonModel{
			Id: param.Id,
		},
	}
	values := map[string]interface{}{
		"is_banned":   param.IsBanned,
		"modified_on": time.Now().Local().Unix(),
	}
	if param.Remark != "" {
		values["remark"] = param.Remark
	}
	return role.Update(tx, values)
}

func (d *Dao) RoleListAll() ([]*model.Role, error) {
	role := model.Role{}
	return role.RoleListAll(d.Engine)
}

// 根据角色ids获取角色
func (d *Dao) GetRolesByRoleIds(roleIds []string) ([]*model.Role, error) {
	role := model.Role{}
	return role.GetRolesByRoleIds(d.Engine, roleIds)
}
